//
//  NetworkTools.swift
//  SinaWeibo
//
//  Created by yang on 15/11/17.
//  Copyright © 2015年 yang. All rights reserved.
//

import UIKit
import AFNetworking
enum HTTPMethod:String{
    case POST = "POST"
    case GET = "GET"
}
let weiboDomain = "com.baidu.data.error"
class NetworkTools: AFHTTPSessionManager {

    static let sharedTools:NetworkTools = {
        let str = "https://api.weibo.com/"
        let url = NSURL(string: str)
        let tools = NetworkTools(baseURL: url)
    tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    func requestJsonDict(method:HTTPMethod,urlString:String,parameters:[String:AnyObject]?,finished:(dict:[String:AnyObject]?,error :NSError?) -> ()){
        if method == HTTPMethod.GET{
        self.GET(urlString, parameters: parameters, success: { (_, result) -> Void in
            if let dict = result as? [String:AnyObject]{
                finished(dict :dict,error:nil)
                return
            }
            let dataError = NSError(domain: weiboDomain, code: -10000, userInfo: [NSLocalizedDescriptionKey:"数据错误"])
            finished(dict: nil, error: dataError)
        }, failure: { (_, error) -> Void in
            finished(dict: nil, error: error)
        })
        }else{
            self.POST(urlString, parameters: parameters, success: { (_, result) -> Void in
                if let dict = result as? [String:AnyObject]{
                    finished(dict :dict,error:nil)
                    return
                }
                let dataError = NSError(domain: weiboDomain, code: -10000, userInfo: [NSLocalizedDescriptionKey:"数据错误"])
                finished(dict: nil, error: dataError)
                }, failure: { (_, error) -> Void in
                   finished(dict: nil, error: error)
            })
        }  
    }
    func uplaodImage(urlString:String,parameters:[String:AnyObject]?,imageData:NSData,finished:(reulst:[String:AnyObject]?,error:NSError?) -> ()){
        POST(urlString, parameters: parameters, constructingBodyWithBlock: { (multipartFormData) -> Void in
             multipartFormData.appendPartWithFileData(imageData, name: "pic", fileName: "OMG", mimeType: "image/jpeg")
            }, success: { (_, reulst) -> Void in
                if let dict = reulst as? [String:AnyObject]{
                     finished(reulst:dict, error: nil)
                }
            }) { (_, error) -> Void in
                finished(reulst: nil, error: error)
        }
    }
}
